<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : DataExtend.php
 * Created on : 2020-10-26 21:43:04
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */
declare (strict_types=1);

namespace haoteam\service;

/**
 * 数据处理扩展
 * Class DataExtend
 * Tiger <1192851302@qq.com> 2020-10-26 21:43:04
 */
class DataExtend {

    /**
     * 一维数组生成数据树
     * @param array $list 待处理数据
     * @param string $cid 自己的主键
     * @param string $pid 上级的主键
     * @param string $sub 子数组名称
     * @return array
     */
    public static function arr2tree(array $list, string $cid = 'id', string $pid = 'pid', string $sub = 'children'): array {
        [$tree, $tmp] = [[], array_combine(array_column($list, $cid), array_values($list))];
        foreach ($list as $vo) {
            isset($vo[$pid]) && isset($tmp[$vo[$pid]]) ? $tmp[$vo[$pid]][$sub][] = &$tmp[$vo[$cid]] : $tree[] = &$tmp[$vo[$cid]];
        }
        unset($tmp, $list);
        return $tree;
    }

    /**
     * 一维数组生成数据树
     * @param array $list 待处理数据
     * @param string $cid 自己的主键
     * @param string $pid 上级的主键
     * @param string $cpath 当前 PATH
     * @param string $ppath 上级 PATH
     * @return array
     */
    public static function arr2table(array $list, string $cid = 'id', string $pid = 'pid', string $cpath = 'path', string $ppath = ''): array {
        $tree = [];
        foreach (static::arr2tree($list, $cid, $pid) as $attr) {
            $attr[$cpath] = "{$ppath}-{$attr[$cid]}";
            $attr['children'] = $attr['children'] ?? [];
            $attr['spc'] = count($attr['children']);
            $attr['spt'] = substr_count($ppath, '-');
            $attr['spl'] = str_repeat("　├　", $attr['spt']);
            $sub = $attr['children'];
            unset($attr['children']);
            $tree[] = $attr;
            if (!empty($sub)) {
                $tree = array_merge($tree, static::arr2table($sub, $cid, $pid, $cpath, $attr[$cpath]));
            }
        }
        return $tree;
    }

    /**
     * 获取数据树子ID集合
     * @param array $list 数据列表
     * @param mixed $value 起始有效ID值
     * @param string $ckey 当前主键ID名称
     * @param string $pkey 上级主键ID名称
     * @return array
     */
    public static function getArrSubIds(array $list, $value = 0, string $ckey = 'id', string $pkey = 'pid'): array {
        $ids = [intval($value)];
        foreach ($list as $vo) {
            if (intval($vo[$pkey]) > 0 && intval($vo[$pkey]) === intval($value)) {
                $ids = array_merge($ids, static::getArrSubIds($list, intval($vo[$ckey]), $ckey, $pkey));
            }
        }
        return $ids;
    }

}
